<script setup lang="ts">
import { onMounted, ref, watch, nextTick } from 'vue'
import { MapComponentProps } from '../MapComponent'
import 'leaflet/dist/leaflet.css'
import { MapContainerType } from '../Constant/MapContainerType'
import { Map, CRS, latLng, tileLayer } from 'leaflet'
import LeafletMapStore from './utils/LeafletMapStore'

// 组件参数
const props = defineProps(MapComponentProps)
const emits = defineEmits(['init'])

const mapContainer = ref()
let map: Map | undefined

// 组件挂载并且可见，初始化地图
onMounted(() => {
    // 为地图容器设置一个唯一id
    ;(<HTMLElement>mapContainer.value).id = 'map' + Date.now() + Math.round(Math.random() * 1000)
    if (props.visible && props.show) {
        initMap()
    }
})

// 组件挂载并且可见，初始化地图
watch([() => props.visible, () => props.show], () => {
    // 地图显示并且没有初始化
    if (props.visible && props.show && !map) {
        initMap()
    } else if (!props.visible) {
        destroyMap()
    }
})

/**
 * 初始化地图
 */
const initMap = () => {
    nextTick(() => {
        _initMap()
    })
}

/**
 * 销毁地图
 */
const destroyMap = () => {
    console.log('销毁地图')
    map && map.remove && map.remove()
    map = undefined
}

/**
 * 初始化地图
 */
const _initMap = () => {
    map = new Map(mapContainer.value.id, {
        crs: CRS.EPSG4326,
        minZoom: 0, //最小缩放值
        maxZoom: 18, //最大缩放值
        center: latLng(30.560407944979296, 115.97852713758685), //注意和其他地图经纬度格式区别
        zoom: 4, //初始缩放值
        zoomControl: false, //是否启用地图缩放控件
        attributionControl: false, //是否启用地图属性控件
    })
    // @ts-ignore
    window.leafletMap = map
    LeafletMapStore.setMap(map)
    // 加载图层
    // tileLayer('https://gac-geo.googlecnapps.cn/maps/vt?lyrs=s,m&gl=CN&x={x}&y={y}&z={z}').addTo(map)
    const urlTianditu = 'http://t{s}.tianditu.com/DataServer?T=img_c&tk=4267820f43926eaf808d61dc07269beb&x={x}&y={y}&l={z}'
    tileLayer(urlTianditu, {
        subdomains: '01234567', // 多子域
        zoomOffset: 1, // 天地图的EPSG4326跟国际wmts差了一级，需要修改一下源码里面的比例尺
    }).addTo(map)

    // const url = "http://172.22.10.21:8080/geoserver/gwc/service/wmts?service=WMTS&request=GetTile&version=1.0.0&style=polygon&tilematrixSet=EPSG%3A4326&format=image%2Fpng&width=256&height=256&layer=one_map%3ADLTB2012_AN&tilematrix=EPSG%3A4326%3A10&tilerow={x}&tilecol={y}"
    // tileLayer(url).addTo(map);
    emits('init', MapContainerType.LeafletMap)
}
</script>

<template>
    <div v-if="visible" v-show="show" ref="mapContainer" class="leaflet-map"></div>
</template>

<style lang="scss" scoped>
@import './css/LeafletMap.scss';
</style>
